import * as types from './types'
import Req from '../util/request'
import tokenHandler from '../util/token'
import jwtDecode from 'jwt-decode'


export function setLoginPageVisible(showLogin) {
	return (dispatch, getState) => {
		dispatch({
			type: types.SET_LOGINPAGE_VISIBLE,
			showLogin
		})
	}
}

export function setUserName(username) {
	return (dispatch, getState) => {
		dispatch({
			type: types.SET_USER_NAME,
			username
		})
	}
}

export function setPassword(password) {
	return (dispatch, getState) => {
		dispatch({
			type: types.SET_PASSWORD,
			password
		})
	}
}

export function setCurrentUser(user) {
  return {
    type: types.SET_CURRENT_USER,
    user
  }
}

export function logout() {
  return (dispatch, getState) => {
    const user = getState().auth.user
    return Req.post('/logout').then(res => {
      localStorage.removeItem('jwtToken')
      tokenHandler(false)
      dispatch(setCurrentUser({}))
    })
  }
}

export function login(user) {
  return (dispatch, getState) => {
  	const user = getState().auth.user
    return Req.post('/login', user).then(res => {
      const token = res.data.token
      localStorage.setItem('jwtToken', token)
      tokenHandler(token)
      dispatch(setLoginPageVisible(false))
      dispatch(setCurrentUser(jwtDecode(token)))
    })
  }
}
